package top.aigoo.project01.controller.wechat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import top.aigoo.project01.entity.PersonInfo;
import top.aigoo.project01.entity.WeChatUser;
import top.aigoo.project01.entity.WechatAuth;
import top.aigoo.project01.entity.dto.ShopExecution;
import top.aigoo.project01.entity.dto.WechatAuthExecution;
import top.aigoo.project01.enums.WechatAuthStateEnum;
import top.aigoo.project01.service.PersonInfoService;
import top.aigoo.project01.service.WechatAuthService;
import top.aigoo.project01.utils.weixin.message.WeiXinUserUtil;
import top.aigoo.project01.utils.weixin.message.pojo.UserAccessToken;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: *
 * 获取关注公众号之后的微信用户信息的接口，
 * 如果在微信浏览器里访问
 * https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxdfdf
 * 这里会将获取到的code之后可以通过code获取access_token，进而获取用户信息
 * 从微信菜单点击后调用的接口，可以在url里增加参数（role_type）来表明是从商家还是从玩家按钮进来的，依次区分登陆后跳转不同的页面
 * * 玩家会跳转到index.html页面
 * * 商家如果没有注册，会跳转到注册页面，否则跳转到任务管理页面
 * * 如果是商家的授权用户登陆，会跳到授权店铺的任务管理页面
 * @Author: Mr.OYSHUO.欧阳大叔  mail:1642302522@qq.com
 * @Version 1.0.0
 * @Date: 2021/9/8 22:55
 */
@Controller
@RequestMapping("wechatlogin")
public class WeiXinLoginController {
    private Logger logger = LoggerFactory.getLogger(WeiXinLoginController.class);
    private static final String FRONTEND = "1";
    private static final String SHOPEND = "2";
    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private WechatAuthService wechatAuthService;

    /**
     * 回调接口，微信服务器会访问这个接口，回传回来code
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/logincheck", method = {RequestMethod.GET})
    public String doGet(HttpServletRequest request, HttpServletResponse response) {
        logger.debug("===weixin login get...");
        //获取微信公众号传递过来的code，通过code获取access_token,进而获取用户信息
        String code = request.getParameter("code");
        //这个state可以用来传我们自定义的信息，方便程序调用，这里也可以不用
        String roleType = request.getParameter("state");
        logger.debug("===weixin login code: " + code);

        WeChatUser user = null;

        String openId = null;

        WechatAuth auth = null;

        if (code != null) {
            UserAccessToken token;
            try {
                //通过code获取access_token
                token = WeiXinUserUtil.getUserAccessToken(code);
                logger.debug("weixin login token:" + token.toString());
                // 通过token获取accessToken
                String accessToken = token.getAccessToken();
                // 通过token获取openId
                openId = token.getOpenId();
                // 通过access_token和openId获取用户昵称等信息
                user = WeiXinUserUtil.getUserInfo(accessToken, openId);
                logger.debug("weixin login user:" + user.toString());
                request.getSession().setAttribute("openId", openId);
                //根据openid,到后台验证是否已经存在这个用户了
                auth = wechatAuthService.getWechatAuthByOpenId(openId);

            } catch (Exception e) {
                logger.error("error in getUserAccessToken or getUserInfo or findByOpenId: " + e.toString());
                e.printStackTrace();
            }
        }
        // ======todo begin======
        // 前面咱们获取到openId后，可以通过它去数据库判断该微信帐号是否在我们网站里有对应的帐号了，
        // 没有的话这里可以自动创建上，直接实现微信与咱们网站的无缝对接。
        // ======todo end======
        logger.debug("weixin login success.");
        logger.debug("login role_type: " + roleType);
        //前端顾客，如果用户点击的是前端展示系统按钮就进入前端展示系统
        if (FRONTEND.equals(roleType)) {
            PersonInfo personInfo = WeiXinUserUtil.getPersonInfoFromRequest(user);
            if (auth == null) {
                //personInfo.setCustomerFlag(1);
                //设置用户类型为顾客
                personInfo.setUserType(1);
                auth = new WechatAuth();
                auth.setOpenId(openId);
                auth.setPersonInfo(personInfo);
                WechatAuthExecution we = wechatAuthService.register2(auth);
                //如果创建失败,就让用户哪儿都不去
                if (we.getState() != WechatAuthStateEnum.SUCCESS.getState()) {
                    return null;
                }
            }
            personInfo = personInfoService.getPersonInfoById(auth.getPersonInfo().getUserId());
            request.getSession().setAttribute("user", personInfo);
            return "frontend/index";
        }
        //商店后台
        //if (SHOPEND.equals(roleType)) {
        //    PersonInfo personInfo = null;
        //    WechatAuthExecution we = null;
        //    if (auth == null) {
        //        auth = new WechatAuth();
        //        auth.setOpenId(openId);
        //        personInfo = WeiXinUserUtil.getPersonInfoFromRequest(user);
        //        //personInfo.setShopOwnerFlag(1);
        //        //设置用户类型为商家
        //        personInfo.setUserType(2);
        //        auth.setPersonInfo(personInfo);
        //        we = wechatAuthService.register2(auth);
        //        if (we.getState() != WechatAuthStateEnum.SUCCESS.getState()) {
        //            return null;
        //        }
        //    }
        //    personInfo = personInfoService.getPersonInfoById(auth.getUserId());
        //    request.getSession().setAttribute("user", personInfo);
        //    ShopExecution se = shopService.getByEmployeeId(personInfo
        //            .getUserId());
        //    request.getSession().setAttribute("user", personInfo);
        //    if (se.getShopList() == null || se.getShopList().size() <= 0) {
        //        return "shop/registershop";
        //    } else {
        //        request.getSession().setAttribute("shopList", se.getShopList());
        //        return "shop/shoplist";
        //    }
        //}
        return null;
    }


}
